<template>
  <view>
    <u-popup :show="show" @close="alertClose" mdoe='bottom' closeable safeAreaInsetBottom>
      <view class="alert">
        <view class="main">
          <u-upload width="300rpx" style="margin: 0 auto" height="300rpx" deletable v-show='changType==0'
            :fileList="fileList1" :maxSize='1024 * 1024 * 2' @afterRead="afterRead" @delete="deletePic" name="1"
            :maxCount="1">
          </u-upload>
          <u--form ref="uForm" errorType="border-bottom" labelPosition="left" :model="model1" :rules="rules">
            <u-form-item v-show='changType==1' class="test" label="昵称" labelWidth="auto" borderBottom
              prop="userInfo.nickname">
              <u--input v-model="model1.userInfo.nickname" border="none"></u--input>
              <text class="hz" style="color: transparent;">@qq.com</text>
            </u-form-item>
            <u-form-item v-show='changType==2' class="test" label="邮箱" labelWidth="auto" borderBottom
              prop="userInfo.email">
              <u--input v-model="model1.userInfo.email" readonly border="none"></u--input>
              <text class="hz">@qq.com</text>
            </u-form-item>
            <u-form-item v-show='changType==2' class="test" label="密码" labelWidth="auto" borderBottom
              prop="userInfo.password">
              <u--input v-model="model1.userInfo.password" border="none"></u--input>
              <text class="hz" style="color: transparent;">@qq.com</text>
            </u-form-item>
            <u-form-item v-show='changType==2' class="test" label="验证码" borderBottom labelWidth="auto"
              prop="userInfo.code">
              <u--input v-model="model1.userInfo.code" border="none"></u--input>
              <u-toast ref="uToast"></u-toast>
              <u-code changeText="x秒后获取" :seconds="seconds" @end="end" @start="start" ref="uCode" @change="codeChange">
              </u-code>
              <u-button class="btncode" @tap="getCode">{{tips}}</u-button>
            </u-form-item>
          </u--form>
          <view @click="modiy" class="sbtn">
            确定修改
          </view>
        </view>
      </view>
    </u-popup>
    <search leftWidth='300' bgColor='black'>
      <blockquote @click='goBack' slot="leftMain">
        <view class="left">
          <u-icon name="arrow-left" color="white" size="28"></u-icon> <text>账号资料</text>
        </view>
      </blockquote>
      <blockquote slot="centerMain">
        <!--        <u--input focus color='white'
          customStyle="width: calc(100vw - 200rpx);borderRadius:20rpx; background:rgba(0,0,0,0.5)" placeholder="请输入搜索内容"
          prefixIcon="search" clearable prefixIconStyle="font-size: 44rpx;color: #909399">
        </u--input> -->
      </blockquote>
      <blockquote slot="rightMain">
        <!--     <text class="sbtn">搜索</text> -->
      </blockquote>
    </search>
    <view class="bmain">
      <view @click="cz(0)" class="item">
        <text>头像</text>
        <blockquote class='mright'>
          <u-avatar size='80' :src="src"></u-avatar>
          <u-icon class='arr' name="arrow-right" size='24'></u-icon>
        </blockquote>
      </view>
      <u-gap height="20" bgColor="#dcdcdc"></u-gap>
      <view class="item">
        <text>ID</text>
        <blockquote class='mright'>
          <text>{{userinfo._id}}</text>
        </blockquote>
      </view>
      <view @click="cz(1)" class="item">
        <text>昵称</text>
        <blockquote class='mright'>
          <text>{{userinfo.nickname}}</text>
          <u-icon class='arr' name="arrow-right" size='24'></u-icon>
        </blockquote>
      </view>
      <view @click="cz(2)" class="item">
        <text>密码</text>
        <blockquote class='mright'>
          <text>修改密码/忘记密码</text>
          <u-icon class='arr' name="arrow-right" size='24'></u-icon>
        </blockquote>
      </view>
    </view>
  </view>
</template>

<script>
  import {
    cmode
  } from '../../env.js'
  import {
    getcode,
    modifyavator,
    modifynickname,
    modifypassword,
    getuserinfo,
    login
  } from '@/api/user.js'
  import search from '@/component/search/search.vue'
  import {
    mapState,
    mapMutations
  } from "vuex"
  export default {
    data() {
      return {
        fileList1: [],
        src: ``,
        show: false,
        tips: '',
        changType: "",
        seconds: 30,
        model1: {
          userInfo: {
            code: "",
            email: "",
            nickname: "",
            password: ""
          },
        },
        rules: {}
      }
    },
    computed: {
      ...mapState("m_login", ["userinfo"])
    },
    onReady() {
      if (this.userinfo.avator) {
        this.src = cmode + this.userinfo.avator
        this.model1.userInfo.email = this.userinfo.email.split('@')[0]
        this.model1.userInfo.nickname = this.userinfo.nickname
      }
    },
    components: {
      search
    },
    methods: {
      ...mapMutations("m_login", ["setUserInfo"]),
      alertClose() {
        this.show = false
        this.fileList1 = []
      },
      // 删除图片
      deletePic(event) {
        this[`fileList${event.name}`].splice(event.index, 1)
      },
      // 新增图片
      async afterRead(event) {
        // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
        let lists = [].concat(event.file)
        let fileListLen = this[`fileList${event.name}`].length
        lists.map((item) => {
          this[`fileList${event.name}`].push({
            ...item,
            status: 'uploading',
            message: '上传中'
          })
        })
        for (let i = 0; i < lists.length; i++) {
          const result = await this.uploadFilePromise(lists[i].url)
          console.log(result);
          let item = this[`fileList${event.name}`][fileListLen]
          this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
            status: 'success',
            message: result.msg,
            url: cmode + '/' + result.data,
            uploadurl: '/' + result.data
          }))
          fileListLen++

        }
      },
      uploadFilePromise(url) {
        return new Promise((resolve, reject) => {
          let a = uni.uploadFile({
            url: `${cmode}/admin/upload`, // 仅为示例，非真实的接口地址
            filePath: url,
            name: 'imgs',
            header: {
              'Authorization': `Bearer ${uni.getStorageSync('token')}`
            },
            // formData: {
            //   user: 'test'
            // },
            success: (res) => {
              console.log(JSON.parse(res.data));
              // setTimeout(() => {
              resolve(JSON.parse(res.data))
              // }, 1000)
            },
            fail(err) {
              console.log(err);
            }
          });
        })
      },
      goBack() {
        this.$Router.back()
      },
      codeChange(text) {
        this.tips = text;
      },
      modiy() {
        switch (this.changType) {
          case 0:
            modifyavator({
              avator: this.fileList1[0].uploadurl
            }).then(res => {
              uni.$u.toast(res.msg)
              if (res.code == 200) {
                this.alertClose()
              }
            })
            break;
          case 1:
            modifynickname({
              nickname: this.model1.userInfo.nickname
            }).then(res => {
              uni.$u.toast(res.msg)
              if (res.code == 200) {
                this.alertClose()
              }
            })
            break;
          case 2:
            // console.log({
            //   code: this.model1.userInfo.code,
            //   password: this.model1.userInfo.password
            // });

            modifypassword({
              code: this.model1.userInfo.code,
              password: this.model1.userInfo.password
            }).then(res => {

              uni.$u.toast(res.msg)
              if (res.code == 200) {
                this.alertClose()
              }
            })
            break;
        }
        getuserinfo().then(res => {
          this.setUserInfo(res.data)
          console.log(res);
          this.src = cmode + this.userinfo.avator
          this.model1.userInfo.email = this.userinfo.email.split('@')[0]
          this.model1.userInfo.nickname = this.userinfo.nickname
        })
      },
      cz(index) {
        this.changType = index
        this.show = true
        switch (index) {
          case 0:
            this.fileList1 = [{
              status: 'success',
              message: 'success',
              url: cmode + this.userinfo.avator
            }]
            break;
          case 1:
            this.rules = {
              'userInfo.nickname': {
                message: "验证码未输入",
                // 自定义验证函数，见上说明
                validator: (rule, value, callback) => {
                  if (value) {
                    return true
                  } else {
                    uni.$u.toast('请输入昵称');
                    return false;
                  }

                },
                // 触发器可以同时用blur和change
                trigger: ['blur'],
              }
            }
            break;
          case 2:
            this.rules = {
              'userInfo.code': {
                message: "验证码未输入",
                // 自定义验证函数，见上说明
                validator: (rule, value, callback) => {
                  if (value) {
                    return true
                  } else {
                    uni.$u.toast('请输入验证码');
                    return false;
                  }

                },
                // 触发器可以同时用blur和change
                trigger: ['blur'],
              },
              'userInfo.password': {
                message: "密码未输入",
                validator: (rule, value, callback) => {
                  if (value) {
                    return true
                  } else {
                    uni.$u.toast('请输入密码');
                    return false;
                  }

                },
                // 触发器可以同时用blur和change
                trigger: ['blur'],
              },
              'userInfo.email': {
                message: "邮箱未输入",
                validator: (rule, value, callback) => {
                  if (value) {
                    return true
                  } else {
                    uni.$u.toast('请输入邮箱');
                    return false;
                  }

                },
                // 触发器可以同时用blur和change
                trigger: ['blur'],

              }
            }
            break;
        }
      },
      register() {
        this.$refs.uForm.validate().then(res => {

        }).catch(errors => {
          uni.$u.toast(errors[0].message)
        })
      },
      getCode() {
        if (this.$refs.uCode.canGetCode) {
          // 模拟向后端请求验证码
          uni.showLoading({
            title: '正在获取验证码'
          })
          getcode({
            type: "注册验证码",
            email: this.model1.userInfo.email + '@qq.com'
          }).then(res => {
            if (res) {
              uni.hideLoading();
              // 这里此提示会被this.start()方法中的提示覆盖
              // uni.$u.toast(res.msg);
              // 通知验证码组件内部开始倒计时
              this.$refs.uCode.start();
              uni.showToast({
                title: res.msg,
                icon: "none"
              })
            }
          })
        } else {
          uni.$u.toast('请求繁忙');
        }

      },
      end() {
        // uni.$u.toast('倒计时结束');
      },
      start() {
        // uni.$u.toast('倒计时开始');
      }
    }
  }
</script>

<style lang="scss" scoped>
  /deep/ .u-form-item__body {
    margin-top: 40rpx;
    font-size: 36rpx !important;
  }

  /deep/ .uicon-close {
    font-size: 20px !important;
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
    left: 3px;
    top: 10px;
  }

  /deep/ .u-upload__deletable {
    width: 20px;
    height: 20px;

  }

  /deep/ .u-button {
    color: white
  }

  /deep/ .u-form-item__body__left__content__label {
    font-size: 36rpx !important;
  }

  .sbtn {
    width: 220rpx;
    height: 80rpx;
    display: flex;
    margin: 4rpx auto;
    border-radius: 20rpx;
    justify-content: center;
    align-items: center;
    background-color: #c00000;
    color: white;
    font-size: 28rpx;
    font-weight: 600;
  }

  .left {
    font-size: 28rpx;
    display: flex;
    align-items: center;
  }

  .alert {
    width: 100%;
    height: 800rpx;
    display: flex;
    justify-content: center;
    align-items: center;

    .main {
      width: 480rpx;
      height: 600rpx;
      display: flex;
      flex-direction: column;
      align-content: space-around;
      justify-content: space-around;


      .btncode {
        width: 180rpx;
        border-radius: 10rpx;
        height: 50rpx;
        color: white !important;
        background: #c00000;
        font-size: 24rpx;
        border: 2rpx solid transparent !important;
      }
    }
  }

  .bmain {
    width: 100vw;
    height: 400rpx;
    margin-top: 30rpx;
    background-color: white;
    color: black;
    display: flex;
    padding: 30rpx 0;
    box-sizing: border-box;
    font-size: 30rpx;
    font-weight: 600;
    flex-direction: column;

    .item:nth-child(1) {
      height: 100rpx;
      margin-bottom: 30rpx;
    }

    .item {
      padding: 0 40rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-top: 30rpx;

      .mright {
        display: flex;

        .arr {
          margin-left: 10rpx;
        }
      }
    }
  }
</style>
